const path = require('path')
const webpack = require('webpack')
const { merge } = require('webpack-merge')
const commonConfig = require('./webpack.common')
const CssExtractPlugin = require('mini-css-extract-plugin')
const TerserWebpackPlugin = require('terser-webpack-plugin')
const postcss = require(path.join(__dirname, '../postcss.config'))
const OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin')
const { CleanWebpackPlugin: CleanPlugin } = require('clean-webpack-plugin')

module.exports = merge(commonConfig, {
  mode: 'production',
  output: {
    filename: 'js/[name]-[contenthash:8].js'
  },
  optimization: {
    minimize: true,
    minimizer: [
      new OptimizeCssPlugin(),
      new TerserWebpackPlugin()
    ],
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        libs: {
          name: 'depend/chunk-libs',
          test: /[\\/]node_modules[\\/]/,
          priority: 10,
          chunks: 'initial' // 只打包初始时依赖的第三方
        },
        elementUI: {
          name: 'depend/chunk-elementUI', // 单独将 elementUI 拆包
          priority: 20, // 权重
          test: /[\\/]node_modules[\\/]element-ui[\\/]/
        },
        vueLibs: {
          name: 'depend/chunk-vue', // 单独将 vue 开头的依赖 拆包
          priority: 15, // 权重
          test: /[\\/]node_modules[\\/]vue/
        },
        commons: {
          name: 'commons/chunk-comomns',
          test: path.join(__dirname, '../common'), // 可自定义拓展你的规则
          // minChunks: 3, // 最小公用次数
          priority: 5,
          reuseExistingChunk: true
        }
      }
    },
    runtimeChunk: 'single'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          CssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                config: path.join(__dirname, '../postcss.config.js')
              }
            }
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          CssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                config: path.join(__dirname, '../postcss.config.js')
              }
            }
          },
          'less-loader'
        ]
      },
    ]
  },
  plugins: [
    new CleanPlugin(),
    new CssExtractPlugin({
      filename: 'css/[name]-[contenthash:8].css'
    })
  ]
})
